package com.zyq.service.impl;

import com.zyq.common.entity.AclPermission;
import com.zyq.common.entity.AclUser;
import com.zyq.feign.SystemFeign;
import com.zyq.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyUserService implements UserDetailsService {
    @Autowired
    private SystemFeign systemFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 通过用户名查询出来用户的基本信息,需要用到system微服务模块的方法
        Result<AclUser> userInfo = systemFeign.getUserInfo(username);
        if(userInfo != null && userInfo.getData() !=null){
            // 2. 再通过用户名查询出来用户的权限信息,
            String id = userInfo.getData().getId();
            String password = userInfo.getData().getPassword();
            Result<List<AclPermission>> permissionInfo = systemFeign.getPermissionInfo(id);
            List<AclPermission> permissions = permissionInfo.getData();
            /*还不会
            *  List<SimpleGrantedAuthority> authorities=permissions.stream()
                                                   //过滤掉不满足条件的元素
                                                  .filter(item->item.getPermissionValue()!=null)
                                                    //把集合中的元素类型转化为SimpleGrantedAuthority类型
                                                  .map(item->new SimpleGrantedAuthority(item.getPermissionValue()))
                                                   .collect(Collectors.toList());
            * */

            if(permissionInfo.getData() != null){
                List<SimpleGrantedAuthority> authorities=permissions.stream()
                        //过滤掉不满足条件的元素
                        .filter(item->item.getPermissionValue()!=null)
                        //把集合中的元素类型转化为SimpleGrantedAuthority类型
                        .map(item->new SimpleGrantedAuthority(item.getPermissionValue()))
                        .collect(Collectors.toList());
                // 将该用户的所有信息封装起来，交由springsecurity进行判断密码是否正确，并存放起来
                User user = new User(username,password,authorities);
                return user;
            }
        }
        return null;
    }
}
